package v1

import (
	"fmt"
	"github.com/gin-gonic/gin"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/models"
	"gitee.com/laofa1/play/k_conf_mng/kconf_backend/pkg/util"
	"log"
	"net/http"
	"strings"
)

type GetConfigParam struct {
	InstanceName string `form:"instanceName" binding:"required,lt=50"`
}
func GetConfig(c *gin.Context) {
	var getConfigParam GetConfigParam
	if err := c.BindQuery(&getConfigParam); err != nil {
		log.Println(err)
		return
	}

	var errMsg string
	temContent, err := models.GetConfTemplateContent("testing")
	if err != nil || temContent == ""{
		log.Println("获取karbon config template内容时错误")
		c.String(http.StatusBadRequest, "获取template内容错误")
		return
	}

	confItemsReplace, err := models.GetConfItemsByInstanceName(getConfigParam.InstanceName)
	if err != nil {
		errMsg = fmt.Sprintf("get config items of instance: %s error: %s", getConfigParam.InstanceName, err.Error())
		log.Println(errMsg)
		c.String(http.StatusBadRequest, errMsg)
		return
	}

	// check config
	content, errMsgList, err := util.CheckAndReplace(temContent, confItemsReplace)
	if err != nil {
		log.Println(err)
		if errMsgList != nil {
			errMsg = strings.Join(errMsgList, ",")
			log.Println(errMsg)
			c.JSON(http.StatusOK, gin.H{
				"status": "error",
				"data": errMsg,
			})
		} else {
			c.JSON(http.StatusOK, gin.H{
				"status": "error",
				"data": err.Error(),
			})
		}
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status": "ok",
		"data": content,
	})
}
